package com.intretech.umsin.datasource.entity;


import com.intretech.umsin.common.utils.CUtils;

import java.util.*;


/**
 * 定义数据库返回的单个数据表
 * @author 李启联
 *
 */
public class DBTable {
	
	public DBTable() {
		super();
	}
	
	/*
	 * 表名称
	 */
	private String tableName;
	
	/*
	 * 表数据
	 */
	private List<Map<String,Object>> data;
	
	public String getTableName() {
		return tableName;
	}
	public void setTableName(String tableName) {
		this.tableName = tableName;
	}
	public List<Map<String,Object>> getData() {
		return data;
	}
	public void setData(List<Map<String,Object>> data) {
		this.data = data;
	}
	@Override
	public String toString() {
		return "DBTable [tableName=" + tableName + ", data=" + data + "]";
	}
	
	/**
	 * 过滤表数据
	 * @param keyName  列名称
	 * @param keyValue 列名称对应的值
	 * @return
	 */
	public List<Map<String,Object>> selectByKey(String keyName,Object keyValue){
		
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();		
		for (Map<String, Object> row : this.data) {
			keyName = CUtils.getMapKeyIgnoreCase(row, keyName);//忽略大小写，防止传入的keyName与实际Map中的Key存在大小写的差异
			if(row.containsKey(keyName) && keyValue.equals(row.get(keyName)) ) {
				list.add(row);
			}
		}	
		return list;
	}
	
	/**
	 * 把数据表以xml的方式输出
	 * @return
	 */
	public String writeToXML() {
		
		List<Map<String, Object>> list = this.data;
		if (list == null)
			return "";

		StringBuilder builder = new StringBuilder();
		for (Map<String, Object> m : list) {
			
			// 通过ArrayList构造函数把map.entrySet()转换成list
			List<Map.Entry<String, Object>> sortList = new ArrayList<Map.Entry<String, Object>>(m.entrySet());
			// 通过比较器实现比较排序
			Collections.sort(sortList, new Comparator<Map.Entry<String, Object>>() {
				public int compare(Map.Entry<String, Object> mapping1, Map.Entry<String, Object> mapping2) {
					return mapping1.getKey().compareTo(mapping2.getKey());
				}
			});

			builder.append("<" + this.getTableName().toLowerCase() + ">");
			builder.append("\n");

			for (Map.Entry<String, Object> mapping : sortList) {
				if (mapping.getValue() != null && mapping.getValue().toString().length() > 0) {
					builder.append("	<" + mapping.getKey().toLowerCase() + ">" + mapping.getValue().toString() + "</"
							+ mapping.getKey().toLowerCase() + ">");
					builder.append("\n");
				}
			}

			/*
			 * for (String k : m.keySet()) { if( m.get(k) != null &&
			 * m.get(k).toString().length() > 0) {
			 * builder.append("	<"+k.toLowerCase()+">"+m.get(k).toString()+"</"+
			 * k.toLowerCase()+">"); builder.append("\n"); } }
			 */
			builder.append("</" + this.getTableName().toLowerCase() + ">");
			builder.append("\n");
		}

		return builder.toString();
		
	}
}
